const wxParse = require('../../templates/wxParse/wxParse');

Page({
  data: {
    // 表单规则
    rules: [{
      name: "name",
      rule: ["required", "isChinese", "minLength:2", "maxLength:6"], // 可使用区间，此处主要测试功能
      msg: ["请输入姓名", "姓名必须全部为中文", "姓名必须2个或以上字符", "姓名不能超过6个字符"]
    }, {
      name: "mobile",
      rule: ["required", "isMobile"],
      msg: ["请输入手机号", "请输入正确的手机号"]
    }, {
      name: "code",
      rule: ["required", "isSame:smsCode"],
      msg: ["请输入验证码", "请核对验证码"]
    }, {
      name: "pwd",
      rule: ["required", "isEnAndNo"],
      msg: ["请输入密码", "密码为8~20位数字和字母组合"]
    }, {
      name: "pwd2",
      rule: ["required", "isSame:pwd"],
      msg: ["请输入确认密码", "两次输入的密码不一致"]
    }],
    mobileValid: false
  },
  onLoad: function () {
    let config = wx.getStorageSync('rf_config');
    this.setData({
      config: config,
      company: config.copyright_companyname,
      windowHeight: wx.getSystemInfoSync()['windowHeight'] - 50
    });
  },
  keyInput: function (e) {
    let valid = false, mobile = e.detail.value;
    if (mobile.length == 11) {
      let rule = [];
      for (let item of this.data.rules) {
        if (item.name == 'mobile') {
          rule.push(item);
          break;
        }
      }
      valid = wx.form.validation(mobile, rule);
    }
    if (this.data.mobileValid != valid) {
      this.setData({
        mobile: mobile,
        mobileValid: valid
      });
    }
  },
  sendSMSCode: function () {
    wx.util.request('auth.smsCode', {body: {
      mobile: this.data.mobile,
      usage: 'register'
    }}).then(code => {
      wx.util.toast('已发送');
      this.setData({
        cd: 60,
        smsCode: code.toString()
      });
    }).catch(err => {
      console.log(err);
    });
  },
  // 倒计时结束
  cdEnd: function () {
    this.setData({
      cd: 0
    });
  },
  regPro: function () {
    this.setData({
      popupShow: true
    });
    wxParse.wxParse('article', 'html', this.data.config.protocol_register, this, 5);
  },
  priPro: function () {
    this.setData({
      popupShow: true
    });
    wxParse.wxParse('article', 'html', this.data.config.protocol_privacy, this, 5);
  },
  hidePopup: function () {
    this.setData({
      popupShow: false
    });
  },
  protocol: function (e) {
    this.setData({
      agreement: e.detail.value[0] == 1
    });
  },
  formSubmit: function (e) {
    // 进行表单检查
    let formData = e.detail.value;
    // 原始短信验证码，用以验证用户输入
    formData.smsCode = this.data.smsCode;
    let checkRes = wx.form.validation(formData, this.data.rules);
    if (!checkRes) {
      wx.user.register(formData);
    } else {
      wx.util.toast(checkRes);
    }
  },
  formReset: function (e) {
    console.log("清空数据")
  }
})